<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <div class="h-150 overflow-y-auto wrapper">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        v-loading="formLoading"
      >
        <el-form-item label="班型名称" prop="spuName">
          <el-input v-model="formData.spuName" placeholder="请输入班型名称" />
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <el-select v-model="formData.carType" placeholder="请选择车辆类型">
            <el-option label="客车" value="客车" />
            <el-option label="货车" value="货车" />
            <el-option label="小车" value="小车" />
            <el-option label="摩托车" value="摩托车" />
            <el-option label="房车" value="房车" />
            <el-option label="残疾人车" value="残疾人车" />
          </el-select>
        </el-form-item>
        <el-form-item label="班型简介">
          <el-input
            :rows="3"
            type="textarea"
            v-model="formData.spuDesc"
            placeholder="请输入班型简介"
          />
        </el-form-item>
        <el-form-item label="原价(元)" prop="originalPrice">
          <el-input type="number" v-model="formData.originalPrice" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="价格(元)" prop="salePrice">
          <el-input type="number" v-model="formData.salePrice" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input type="number" v-model="formData.sortNo" placeholder="请输入排序字段" />
        </el-form-item>
        <el-form-item label="总库存" prop="totalStock">
          <el-input type="number" v-model="formData.totalStock" placeholder="请输入总库存" />
        </el-form-item>
        <el-form-item label="是否展示库存">
          <el-radio-group v-model="formData.isShowStock">
            <el-radio :label="true">展示</el-radio>
            <el-radio :label="false">不展示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="销量" prop="salesCount">
          <el-input type="number" v-model="formData.salesCount" placeholder="请输入销量" />
        </el-form-item>
        <el-form-item label="虚拟销量" prop="virtualSalesCount">
          <el-input
            type="number"
            v-model="formData.virtualSalesCount"
            placeholder="请输入虚拟销量"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="班型缩略图" prop="coverUrl">
          <UploadImg v-model="coverUrl" />
        </el-form-item>
        <el-form-item label="班型轮播图" prop="picUrls">
          <UploadImgs v-model="picUrls" />
        </el-form-item>
        <el-form-item label="班型详情页" prop="detail">
          <Editor v-model="formData.detail" height="500px" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as SpuApi from '@/api/client-mall/product/spu'
import { UploadImg, UploadImgs } from '@/components/UploadFile/index'
import { getOSSURL } from '@/utils/oss'
import useFormData from '@/hooks/ec/useFormData'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formRef = ref({}) // 表单 Ref
const { formData, formRules, resetFormData } = useFormData<{
  id: string | null
  categoryId: string | null
  carType: string | null
  spuName: string | null
  spuDesc: string | null
  tags: string
  detail: string | null
  picUrls: string
  coverUrl: string | null
  originalPrice: number | null
  salePrice: number | null
  totalStock: number
  isShowStock: boolean
  salesCount: number
  virtualSalesCount: number
  status: 1 | 2 // 1:上架 2:下架
  sortNo: number
  spuType: 1 | 2
}>({
  id: {
    defaultValue: null
  },
  categoryId: {
    defaultValue: null
  },
  carType: {
    defaultValue: null,
    rules: [{ required: true, message: '车辆类型不能为空', trigger: 'blur' }]
  },
  spuName: {
    defaultValue: null,
    rules: [{ required: true, message: '班型名称不能为空', trigger: 'blur' }]
  },
  spuDesc: {
    defaultValue: null,
    rules: [{ required: true, message: '班型简介不能为空', trigger: 'blur' }]
  },
  tags: {
    defaultValue: '[]'
  },
  detail: {
    defaultValue: null,
    rules: [{ required: true, message: '班型详情不能为空', trigger: 'blur' }]
  },
  picUrls: {
    defaultValue: '[]',
    rules: [{ required: true, message: '班型轮播图不能为空', trigger: 'blur' }]
  },
  coverUrl: {
    defaultValue: null,
    rules: [{ required: true, message: '班型缩略图不能为空', trigger: 'blur' }]
  },
  originalPrice: {
    defaultValue: null,
    rules: [{ required: true, message: '原价不能为空', trigger: 'blur' }]
  },
  salePrice: {
    defaultValue: null,
    rules: [{ required: true, message: '销售价格不能为空', trigger: 'blur' }]
  },
  totalStock: {
    defaultValue: 999,
    rules: [{ required: true, message: '总库存不能为空', trigger: 'blur' }]
  },
  isShowStock: {
    defaultValue: true,
    rules: [{ required: true, message: '是否展示库存不能为空', trigger: 'blur' }]
  },
  salesCount: {
    defaultValue: 0,
    rules: [{ required: true, message: '销量不能为空', trigger: 'blur' }]
  },
  virtualSalesCount: {
    defaultValue: 0,
    rules: [{ required: true, message: '虚拟销量不能为空', trigger: 'blur' }]
  },
  status: {
    defaultValue: 1,
    rules: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
  },
  sortNo: {
    defaultValue: 0,
    rules: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  },
  spuType: {
    defaultValue: 1,
    rules: [{ required: true, message: '班型类型不能为空', trigger: 'blur' }]
  }
}) // 表单数据

const coverUrl = computed({
  get() {
    return getOSSURL(formData.value.coverUrl || '')
  },
  set(val) {
    formData.value.coverUrl = val
  }
})

const picUrls = computed({
  get() {
    return JSON.parse(formData.value.picUrls || '[]')?.map((item) => ({ url: item }))
  },
  set(val) {
    formData.value.picUrls = JSON.stringify(val.map((item) => item.url))
  }
})

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SpuApi.getSpu(id)
      formData.value.originalPrice = formData.value.originalPrice
        ? formData.value.originalPrice / 100
        : 0
      formData.value.salePrice = formData.value.salePrice ? formData.value.salePrice / 100 : 0
      console.log('formData', formData.value)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SpuApi.SpuVO
    const newData = {
      ...data,
      originalPrice: data.originalPrice * 100,
      salePrice: data.salePrice * 100
    }
    if (formType.value === 'create') {
      await SpuApi.createSpu(newData)
      message.success(t('common.createSuccess'))
    } else {
      console.log('更新: ', newData)
      await SpuApi.updateSpu(newData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  resetFormData()
  formRef.value?.resetFields()
}
</script>
